package sword_offer;

import java.util.Arrays;

/**
 * @author Synhard
 * @version 1.0
 * @Class sword_offer.Code5
 * @Description 从尾到头打印链表
 * 输入：head = [1,3,2]
 * 输出：[2,3,1]
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-03-12 20:09
 */
public class Code5 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(3);
        head.next.next = new ListNode(2);
        System.out.println(Arrays.toString(reversePrint(head)));
    }

    public static int[] reversePrint(ListNode head) {
        ListNode p = reverse(head);
        int[] arr = new int[10000];
        int counter = 0;
        for (int i = 0; i < arr.length && p != null; i++, p = p.next) {
            counter++;
            arr[i] = p.val;
        }
        return Arrays.copyOf(arr, counter);
    }

    public static ListNode reverse(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
